const express = require("express");
const router = express.Router();
const { User } = require("../../models");
const { Op } = require("sequelize");
const {
  BadRequestError,
  UnauthorizedError,
  NotFoundError,
  success,
  failure
} = require("../../utils/response");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
/**
 * 管理登录
 * POST /admin/auth/sign_in
 */
router.post("/sign_in", async (req, res, next) => {
  try {
    const { login, password } = req.body;

    if (!login || !password) {
      throw new BadRequestError("用户名或密码不能为空");
    }
    // 查询条件
    const condition = {
      where: {
        [Op.or]: [{ username: login }, { email: login }],
      },
    };
    
    // 通过email或用户名查询用户
    const user = await User.findOne(condition);
    console.log(password, user.password,'password, user.password')
    if (!user) {
      throw new NotFoundError("用户不存在");
    }
   // 验证密码 之前密码加密所以需要解密
   const isPasswordValid = bcrypt.compareSync(password, user.password);
   if (!isPasswordValid) {
     throw new UnauthorizedError("密码错误");
   }

   //生成身份验证令牌
   const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET_KEY, {
       expiresIn: '1h'
   })

    success(res, "登录成功", {token});
  } catch (error) {
    failure(res, error);
  }
});
module.exports = router;